package com.itheima.dubbo.api.mongo.impl;

import com.itheima.dubbo.api.mongo.UserLikeApi;
import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId,Long likeUserId,boolean isLike) {
        UserLike userLike  = new UserLike();
        userLike.setUserId(userId);
        userLike.setLikeUserId(likeUserId);
        userLike.setIsLike(isLike);
        userLike.setCreated(System.currentTimeMillis());
        userLike.setUpdated(System.currentTimeMillis());
        mongoTemplate.save(userLike);
    }

    //检查是否相互喜欢
    @Override
    public boolean eachLove(Long userId, Long likeUserId) {
        Query query1 = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId).and("isLike").is(true));
        Query query2 = new Query(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId).and("isLike").is(true));
        boolean exists1 = mongoTemplate.exists(query1, UserLike.class);
        boolean exists2 = mongoTemplate.exists(query2, UserLike.class);
        if(exists1&&exists2){
            return true;
        }
        return false;
    }

    //删除喜欢相互的数据
    @Override
    public void deleteEachLove(Long userId, Long likeUserId) {
        Query query1 = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId).and("isLike").is(true));
        Query query2 = new Query(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId).and("isLike").is(true));
        mongoTemplate.remove(query1,UserLike.class);
        mongoTemplate.remove(query2,UserLike.class);
    }
}
